var salt = sessionStorage.getItem('usersalt');
var maxEstimateNum = 0;
var optionType = 0;
var id = getQueryVariable("id");
var userName = getQueryVariable("userName");
var questionList = [];
var sortType;
var indexNow = 0;

$(".name_box .name span").text(userName);
var app = new Vue({
    el: '.body',
    data: {
        info: '',
        baseurl:url,
    },
    updated: function () {
        var that = this;
        questionList.forEach(function (item, index) {
            if (item.id == that.info.id) {
                $(".num").text(index + 1);
                return
            }
        })
        var answer = questionList[indexNow].answer;
        if(answer){
          $(".option").each(function () {
            if(answer.indexOf($(this).find("i").text().substring(0,1)) != -1){
                if(questionList[indexNow].questionType == 1){
                    $(this).find("input[type=checkbox]").prop("checked",true);
                }else{
                    $(this).find("input[type=radio]").prop("checked",true);
                }
            }else{
                if(questionList[indexNow].questionType == 1){
                    $(this).find("input[type=checkbox]").prop("checked",false);
                }else{
                    $(this).find("input[type=radio]").prop("checked",false);
                }
            }
          })
        }else{
          $(".option input[type=checkbox]").prop("checked",false);
            $(".option input[type=radio]").prop("checked",false);
        }
      layui.use(['form'], function () {
        var form = layui.form;
        form.render()
      });
    }
})
var maxtime;
function CountDown() {
    if (maxtime >= 0) {
        minutes = Math.floor(maxtime / 60);
        seconds = Math.floor(maxtime % 60);
        msg = "距离结束还有" + minutes + "分" + seconds + "秒";
        $(".name_box .time span").text(minutes+"min "+seconds+"s");
        --maxtime;
    } else {
        clearInterval(timer);
      submitAnswer("考试结束，试卷自动提交成功");
    }
}


$.post(url + "questionPaper/getInfo", {id: id, Token: salt}, function (data) {
    if (data.code == 0) {
        var data = data.data;
        initQuestion(data);
    } else {
        alert(data.msg)
    }
});


function initQuestion(data) {
    $(".question_name").text(data.title);

    //题目排序 0:单选，1：多选，2：判断
    sortType = data.sortType.split("—");
    sortType.splice(sortType.indexOf("单选"), 1, "radioQuestion");
    sortType.splice(sortType.indexOf("多选"), 1, "multiSelectQuestion");
    sortType.splice(sortType.indexOf("判断"), 1, "tfngQuestion");
    sortType.forEach(function (item) {
        data[item].forEach(function (list, index) {
            list.options = JSON.parse(list.options);
            if(list.fileId){
              list.fileId = list.fileId.split(",");
            }
          if(list.parseFileId){
            list.parseFileId = list.parseFileId.split(",");
          }
            list.options.forEach(function (it) {
                if(it.fileId){
                    it.fileId = it.fileId.split(",");
                }

            })
            questionList.push(list);
        })
    })
    app.info = questionList[0];
    // resetTime(data.duration*60);
    maxtime = data.duration*60;
    timer = setInterval("CountDown()", 1000)
}


layui.use(['form', 'layer', 'laydate', 'table', 'laytpl'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;

    if (!sessionStorage.getItem('username')) {
        layer.msg('请先登录');
        setTimeout("top.location.href='../../../index.html'", 1000);
    }


    form.on('checkbox', function (data) {
        var id = $(this).attr("id")
        var questionType = $(this).attr("questionType")
        questionList.forEach(function (item) {
            if (item.id == id) {
                var answer = [];
                $(".option input[type=checkbox]:checked").each(function () {
                    answer.push($(this).prev().text());
                })
                item.answer = answer;
            }
        })
        console.log(questionList)
    });

    form.on('radio', function (data) {
        var id = $(this).attr("id")
        var questionType = $(this).attr("questionType")
        questionList.forEach(function (item) {
            if (item.id == id) {
                var answer = [];
                answer.push( $(".option input[type=radio]:checked").prev().text());
                item.answer = answer;
            }
        })
        console.log(questionList)
    });

});

var checkId = getQueryVariable("id");
var editCompanyId;


var company;


$("body").on("click", ".model .button button", function () {
    $(".model").hide()
});

var letterArr = [];
for (var i = 65, j = 0; i < 91; i++, j++) {
    letterArr[j] = String.fromCharCode(i);
}

//选项排序
sortOption()
function sortOption() {
    $(".option label").each(function (i) {
        $(this).text(letterArr[i]);
    })
    if (optionType == 2) {
        $(".type_option input").hide().siblings().show();
        $(".add_option").hide();
    } else {
        $(".type_option input").show().siblings().hide();
        $(".add_option").show();
    }

    layui.use(['form'], function () {
        var form = layui.form;
        form.render('checkbox')
    });
}

//添加选项
$("body").on("click", ".add_option .box", function () {
    var str = '<div class="layui-input-block option">' +
        '<label></label><input type="checkbox" name="like1[write]" lay-skin="primary">' +
        '<span class="type_option">' +
        '<input type="text" name="title" lay-verify="title" autocomplete="off" placeholder="请输入标题"' +
        'class="layui-input option_input"><span>错误</span></span>' +
        '<i class="seraph icon-guanbi"></i>' +
        '<span class="true">【正解】</span><div><button type="button" class="layui-btn file">选择文件</button></div>';
    $(".add_option").before(str);
    sortOption();
})


//删除选项
$("body").on("click", ".icon-guanbi", function () {
    if ($(".option").length > 2) {
        $(this).parents(".option").remove();
    }
    sortOption()
});

//首题
$("body").on("click", ".first", function () {
    if(indexNow == 0){
        return
    }
    indexNow = 0;
    clearInput();
    app.info = questionList[0];
});
$("body").on("click", ".last", function () {
    if(indexNow == questionList.length - 1){
        return
    }
  indexNow = questionList.length - 1;
    clearInput();
    app.info = questionList[questionList.length - 1];
});
$("body").on("click", ".prev", function () {
    if (indexNow > 0) {
        indexNow--;
        clearInput();
        app.info = questionList[indexNow];
    } else {
        alert("当前是第一个题目！");
    }
});
$("body").on("click", ".next", function () {
    if (indexNow < questionList.length - 1) {
        indexNow++;
        clearInput();
        app.info = questionList[indexNow];
    } else {
        alert("当前是最后一个题目！");
    }
});
//0:单选，1：多选，2：判断
$("body").on("click", ".submit", function () {
    submitAnswer("试卷提交成功");
});

function submitAnswer(msg) {
  var radioAnswer = [];
  var multiSelectAnswer = [];
  var tfngAnswer = [];
  questionList.forEach(function (item) {
    var answer = JSON.stringify({questionId: item.id, answer: item.answer ? item.answer.toString() : ''});
    if (item.questionType == 0) {
      radioAnswer.push(answer)
    } else if (item.questionType == 1) {
      multiSelectAnswer.push(answer)
    } else if (item.questionType == 2) {
      tfngAnswer.push(answer)
    }
  });
  $.post(url + 'questionUser/submitAnswer', {
        Token: salt,
        questionPaperId: id,
        radioAnswer: "[" + radioAnswer.toString() + "]",
        multiSelectAnswer: "[" + multiSelectAnswer.toString() + "]",
        tfngAnswer: "[" + tfngAnswer.toString() + "]"
      },
      function (data) {
        if (data.code == 0) {
          layer.alert(msg, {
            btn: ['确定'] //按钮
          }, function (index) {
            layer.close(index);
            history.go(-1);
          });
        } else {
          alert(data.msg);
        }
      })
}


function clearInput() {
    $(".layui-form-radio,.layui-form-checkbox").remove()
}












